# This file is part of the Net::Tube module.
#
# Net::Tube is Free Software; you can use, redistribute it and/or
# modify it under the terms of either:
#
# a) the GNU General Public License as published by the Free Software
#    Foundation, either version 2, or (at your opinion) any later
#    version, or
#
# b) the "Artistic License" which comes with Perl.
#
package Net::Tube::Filter::SemanticMerge;

use Net::Tube;
our @ISA = qw(Net::Tube::Filter);

use XML::LibXML;

sub bucket_merge {
    my $self      = shift;
    my $oldbucket = shift;

    my $bucket = $self->create_bucket($oldbucket);

    if ( defined $oldbucket ) {
        # warn "oldbucket is defined";
        my $me    = $self->get_config_entry('mergeElements');
        my @nodes = ();

        my $doc = XML::LibXML->createDocument();

        foreach my $xp (@$me) {
            # warn "fetch! using $xp";
            my $xno = $oldbucket->find_nodes($xp);
            next unless defined $xno;
            push @nodes, @$xno;
        }

        my $e;
        # warn "got " . scalar(@nodes) . " nodes";
        foreach my $node (@nodes) {
            unless ( $doc->documentElement ) {
                my $te;
                my $par = $node->parentNode;
                while ( $par && $par->nodeType == XML_ELEMENT_NODE ) {
                    my $tmp = $par->cloneNode(0);
                    if (defined $te) {
                        $tmp->appendChild($te);
                    }
                    else {
                        $e = $tmp;
                    }
                    $te  = $tmp;
                    $par = $par->parentNode;
                }
                my $de;
                if ($te) {
                    $de = $doc->adoptNode($te);
                }
                else {
                    $de = $doc->createElement('merge');
                    $e  = $de;
                }
                
                $doc->setDocumentElement($de);
                $bucket->add_node($doc);    
            }
            last unless $e;
            $e->appendChild( $doc->adoptNode($node) );
        }
    }
    return $bucket;
}

sub process {
    my $self   = shift;
    my $bucket = $self->SUPER::process(@_);
    return $self->bucket_merge($bucket);
}

1;
